class CaptchaController < ApplicationController
  def create
    user = User.registered.find_by(mobile: params[:mobile])
    if user.blank?
      send_sms("create")
      render json: Success.new
    else
      render json: Failure.new("该手机号码已经注册")
    end
  end

  def update
    user = User.registered.find_by(mobile: params[:mobile])
    if user.present?
      send_sms("update")
      render json: Success.new
    else
      render json: Failure.new("该手机号码还未注册")
    end
  end


  def quick
    user = User.registered.find_by(mobile: params[:mobile])
    if user.present?
      send_sms("quick")
      render json: Success.new
    else
      render json: Failure.new("该手机号码还未注册")
    end
  end

  def check
    captcha_info = Rails.cache.fetch(params[:mobile])
    if captcha_info.blank?
      render json: Failure.new("验证码已过期")
    else
      captcha = captcha_info[:captcha]
      if captcha.eql?(params[:code])
        Rails.cache.delete(params[:mobile])
        case captcha_info[:action]
          when "create"
            user = User.find_by(mobile: params[:mobile])
            if user.blank?
              user = User.new(user_params.merge(mobile: params[:mobile], name: params[:mobile], status: 1))
              if user.save
                render json: Success.new(user: user)
              else
                render json: Failure.new(user.errors.full_messages.join(";"))
              end
            else
              if user.update(user_params.merge(status: 1))
                render json: Success.new(user: user)
              else
                render json: Failure.new(user.errors.full_messages.join(";"))
              end
            end
          when "update"
            user = User.find_by(mobile: params[:mobile])
            if user.update(user_params)
              render json: Success.new(user: user)
            else
              render json: Failure.new(user.errors.full_messages.join(";"))
            end
          when "quick"
            user = User.find_by(mobile: params[:mobile])
            if user.blank?
              render json: Success.new("您还未注册")
            else
              user.update(device_type: params[:device_type], device_token: params[:device_token])
              Rails.cache.write(user.token, user)
              render json: Success.new(user: user)
            end
          else
            render json: Failure.new("无效的请求")
        end
      else
        render json: Failure.new("无效的验证码")
      end
    end
  end

  protected
  def user_params
    params.permit(:password, :re_password)
  end


  def send_sms(action)
    sample_str = %w"0 1 2 3 4 5 6 7 8 9"
    captcha = sample_str.sample(6).join
    SmsJob.perform_now(params[:mobile], $template[:captcha], ["#{captcha}", '30分钟'])
    Rails.cache.write(params[:mobile], {action: action, captcha: captcha}, expires_in: 30.minutes)
  end
end
